<template>
  <div id="userInfoPage">
    <a-card title="个人信息" style="max-width: 750px; margin: 0 auto;">
      <a-row :gutter="32">
        <!-- 头像区域 -->
        <a-col :span="8" class="avatar-col">
          <div class="avatar-wrapper">
            <img v-if="form.userAvatar" :src="form.userAvatar" alt="avatar" class="avatar-img" />
            <div v-else class="avatar-placeholder">
              <plus-outlined />
              <div>上传头像</div>
            </div>

            <!-- 文件输入 -->
            <a-upload
              list-type="button"
              :show-upload-list="false"
              :customRequest="handleUpload"
              accept="image/*"
              :beforeUpload="beforeUpload"
              class="upload-trigger"
            >
              <input type="file" ref="fileInputRef" hidden @change="triggerUpload" />
              <a-button type="primary">{{ form.userAvatar ? '修改头像' : '上传头像' }}</a-button>
            </a-upload>

            <!-- 裁剪预览 -->
            <div v-if="previewVisible" class="preview-mask">
              <img :src="previewImage" alt="预览" class="preview-image" />
            </div>
          </div>
        </a-col>

        <!-- 表单区域 -->
        <a-col :span="16">
          <a-form :model="form" layout="vertical" ref="formRef" @finish="onFinish">
            <!-- 用户名 -->
            <a-form-item label="用户名" name="userName" :rules="[{ required: true, message: '请输入用户名' }]">
              <a-input v-model:value="form.userName" placeholder="请输入用户名" />
            </a-form-item>

            <!-- 用户账号（不可编辑） -->
            <a-form-item label="用户账号" name="userAccount">
              <a-input v-model:value="form.userAccount" disabled />
            </a-form-item>

            <!-- 个人简介 -->
            <a-form-item label="个人简介" name="userProfile">
              <a-textarea v-model:value="form.userProfile" placeholder="请输入个人简介" :rows="4" />
            </a-form-item>

            <!-- 提交按钮 -->
            <a-button type="primary" html-type="submit" block>保存修改</a-button>
          </a-form>
        </a-col>
      </a-row>
    </a-card>

    <!-- 图片预览 Modal -->
    <a-modal :visible="previewVisible" title="头像预览" footer="" @cancel="previewVisible = false">
      <img :src="previewImage" alt="预览" style="width: 100%" />
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { getUserInfoVoUsingGet, updateUserInfoUsingPost } from '@/api/userController'
import { uploadUserAvatarUsingPost } from '@/api/fileController'
import { message } from 'ant-design-vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import { useLoginUserStore } from '@/stores/useLoginUserStore'
const userLoginStore = useLoginUserStore()
// 表单数据结构
interface UserInfoForm {
  id?: number
  userName?: string
  userAccount?: string
  userAvatar?: string
  userProfile?: string
}

const form = ref<UserInfoForm>({})
const previewVisible = ref(false)
const previewImage = ref('')
const fileInputRef = ref<HTMLInputElement | null>(null)
const formRef = ref()
// 获取用户信息
const fetchUserInfo = async () => {
  try {
    const res = await getUserInfoVoUsingGet()
    if (res.data.code === 0) {
      form.value = {
        id: res.data.data?.id,
        userName: res.data.data?.userName,
        userAccount: res.data.data?.userAccount,
        userAvatar: res.data.data?.userAvatar,
        userProfile: res.data.data?.userProfile,
      }
    } else {
      message.error('获取用户信息失败: ' + res.data.message)
    }
  } catch (error) {
    console.error('获取用户信息失败', error)
    message.error('网络异常，请稍后再试')
  }
}

// 上传前检查
const beforeUpload = (file: File) => {
  const isValidType = ['image/jpeg', 'image/png', 'image/gif'].includes(file.type)
  const isValidSize = file.size / 1024 / 1024 < 2 // 小于 2MB

  if (!isValidType) {
    message.error('只能上传 JPG/PNG/GIF 格式图片!')
    return false
  }

  if (!isValidSize) {
    message.error('图片大小不能超过 2MB!')
    return false
  }

  return true
}

// 自定义上传方法（上传到服务器）
const handleUpload = async (info: any) => {
  const file = info.file

  try {
    const res = await uploadUserAvatarUsingPost({}, file)
    if (res.data.code === 0 && res.data.data) {
      console.log('上传成功，头像地址为:', res.data.data)
      message.success('上传成功')
      form.value.userAvatar = res.data.data
      previewImage.value = res.data.data
      previewVisible.value = true
      userLoginStore.setLoginUser( {
        ...userLoginStore.loginUser,
        userAvatar: res.data.data,
      })
    } else {
      message.error('上传失败: ' + res.data.message)
    }
  } catch (error) {
    console.error('上传失败', error)
    message.error('上传失败，请重试')
  }
}

// 模拟点击上传控件
const triggerUpload = () => {
  if (fileInputRef.value) {
    fileInputRef.value.click()
  }
}

// 提交表单
const onFinish = async () => {
  try {
    const res = await updateUserInfoUsingPost({
      userAvatar: form.value.userAvatar,
      userName: form.value.userName,
      userProfile: form.value.userProfile,
    })

    if (res.data.code === 0) {
      message.success('保存成功')
      userLoginStore.setLoginUser({
        ...userLoginStore.loginUser,
        userAvatar: form.value.userAvatar,
        userName: form.value.userName,
        userProfile: form.value.userProfile,
      })
      await fetchUserInfo()
    } else {
      message.error('保存失败: ' + res.data.message)
    }
  } catch (error) {
    console.error('保存失败', error)
    message.error('保存失败，请重试')
  }
}

fetchUserInfo()
</script>

<style scoped>
#userInfoPage {
  padding: 24px;
}

.avatar-col {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.avatar-wrapper {
  position: relative;
  text-align: center;
}

.avatar-img {
  width: 150px;
  height: 150px;
  object-fit: cover;
  border-radius: 50%;
  margin-bottom: 16px;
}

.avatar-placeholder {
  width: 150px;
  height: 150px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  border: 1px dashed #d9d9d9;
  border-radius: 50%;
  background-color: #fafafa;
  color: #999;
  font-size: 14px;
}

.upload-trigger {
  width: 150px;
  cursor: pointer;
}

.preview-mask {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.4);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}

.preview-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 50%;
}
</style>
